<template>
  <ChatContainer
    class="chat-container"
    title="DeepSeek 打字机模式"
    :messages="messages"
    :loading="loading"
    v-model:streamMode="streamMode"
    :modelOptions="modelOptions"
    v-model:currentModel="currentModel"
    @send="handleSend"
    @stop="handleStop"
    @clear="handleClear"
    @modelChange="handleModelChange"
  />
  <el-dialog
    v-model="createOpenAIDialogVisible"
    title="请输入OpenAI API Key"
    width="500"
    align-center
  >
    <el-input
      v-model="apiKey"
      @keyup.enter.exact="createAIService"
      placeholder="请输入OpenAI API Key"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="createOpenAIDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createAIService"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue";
import ChatContainer from "@/components/chat/ChatContainer.vue";
import type { Message } from "@/types";
import { ModelType, getAiService, AIChatService } from "@/services/aiService";
import { ElMessage } from "element-plus";
const streamMode = ref(false);
let aiServiceChat: AIChatService | undefined = undefined;
const apiKey = ref("");
const createOpenAIDialogVisible = ref(false);
const createAIService = () => {
  if (!apiKey.value) {
    ElMessage.error("请输入apiKey");
  }
  const aiChat = getAiService({
    apiKey: apiKey.value,
    baseURL: "https://api.deepseek.com/v1",
  });
  if (aiChat) {
    ElMessage.success("创建成功");
    aiServiceChat = aiChat;
    createOpenAIDialogVisible.value = false;
  } else {
    ElMessage.error("创建失败");
  }
};
const loading = ref(false);
const messages = ref<Message[]>([
  {
    role: "system",
    state: "done",
    content: "你好，我是 DeepSeek，你可以向我提问任何问题。",
  },
]);
const handleSend = async (message: string) => {
  if (!aiServiceChat) {
    createOpenAIDialogVisible.value = true;
    return;
  }
  messages.value.push({
    role: "user",
    state: "loading",
    content: message,
  });
  loading.value = true;
  try {
    const assistantMessage = {
      role: "assistant" as const,
      state: "loading",
      content: "",
    };
    messages.value.push(JSON.parse(JSON.stringify(assistantMessage)));
    // 流式回调处理
    const streamCallback = (chunk: string) => {
      assistantMessage.content += chunk;
      // assistantMessage.state = "done";
      messages.value[messages.value.length - 1] = JSON.parse(
        JSON.stringify(assistantMessage)
      );
    };
    if (streamMode.value) {
      await aiServiceChat.streamChat(
        messages.value.slice(0, -1),
        streamCallback,
        () => {
          assistantMessage.state = "done";
          messages.value[messages.value.length - 1] = JSON.parse(
            JSON.stringify(assistantMessage)
          );
        }
      );
    } else {
      const message = await aiServiceChat.chat(messages.value.slice(0, -1));
      assistantMessage.content = message;
      assistantMessage.state = "done";
      messages.value[messages.value.length - 1] = JSON.parse(
        JSON.stringify(assistantMessage)
      );
    }
  } catch (error) {
    ElMessage({
      message: "发送消息失败，请重试",
      type: "error",
      plain: true,
      duration: 2000,
    });
    messages.value.pop();
  } finally {
    loading.value = false;
  }
};
const handleStop = () => {
  loading.value = false;
  messages.value[messages.value.length - 1].content = "已终止";
  messages.value[messages.value.length - 1].state = "done";
  aiServiceChat?.abortStreamChat();
};
const handleClear = async () => {
  messages.value = [
    {
      role: "assistant",
      state: "done",
      content: "你好，我是 DeepSeek，你可以向我提问任何问题。",
    },
  ];
};
// 模型选项
const modelOptions = {
  [ModelType.Chat]: "DeepSeek-V3 (通用对话)",
  [ModelType.Reasoner]: "DeepSeek-R1 (推理增强)",
};

// 当前选择的模型
const currentModel = ref<ModelType>(ModelType.Chat);
const handleModelChange = (model: ModelType) => {
  // currentModel.value = model;
  aiServiceChat?.updateModel(model);
};
</script>

<style scoped>
.chat-container {
  height: 100vh;
}
</style>
